package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        //转换成Department对象
        String s = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(s,Department.class);

        //判断是否存在此科室,根据医院编号和科室编号来查询
        Department departmentExist = departmentRepository.
                getDepartmentByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());

        //判断
        if(departmentExist != null){  //存在
            departmentExist.setUpdateTime(new Date());
            departmentExist.setIsDeleted(0);
            departmentRepository.save(departmentExist);
        }else{
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        //创建Pageable，设置当前页和每页记录数,参数中当前页为0，所以需要减一
        Pageable pageable = PageRequest.of(page-1,limit);
        //创建example
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Department> example = Example.of(department,matcher);
        Page<Department> all = departmentRepository.findAll(example,pageable);
        return all;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        //先判断库中有没有
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(department != null){
            //删除
            departmentRepository.deleteById(department.getId());
        }
    }

    //根据医院编号，查询科室列表，返回树形结构
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //创建list集合，封装最终数据
        List<DepartmentVo> result = new ArrayList<>();

        //根据医院编号查询所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        //所有科室列表信息，含大科室和小科室，但是现在不是树形结构
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据编号（bigcode）先找到所有大科室再分组，然后找大科室里的小科室
        //先遍历，再分组，java8stram流操作,String是大科室编号（bigcode），List<Department>是相同bigcode的小科室集合
        Map<String, List<Department>> deparmentMap
                = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //遍历map集合
        for(Map.Entry<String, List<Department>> entry : deparmentMap.entrySet()){
            //大科室编号
            String bigcode = entry.getKey();
            //大科室编号对应的全部小科室
            List<Department> department1List = entry.getValue();

            //封装大科室
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepname(bigcode);
            departmentVo1.setDepname(department1List.get(0).getBigname());  //从子科室中取出大科室的名字

            //封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for(Department department : department1List){
                DepartmentVo departmentVo2 = new DepartmentVo();
                departmentVo2.setDepcode(department.getDepcode());
                departmentVo2.setDepname(department.getDepname());
                //封装到list集合中
                children.add(departmentVo2);
            }

            //把小科室集合放到大科室集合里面
            departmentVo1.setChildren(children);

            //放入最终result里面
            result.add(departmentVo1);
        }
        return result;
    }

    //根据医院编号和科室编号返回科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department departmentByHoscodeAndDepcode = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(departmentByHoscodeAndDepcode != null){
            return departmentByHoscodeAndDepcode.getDepname();
        }
        return null;
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }
}
